package com.informationsystem.dao.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;

import com.informationsystem.model.Authority;
import com.informationsystem.model.Systemuser;
import com.informationsystem.model.User;
import com.informationsystem.service.UserSecurityAdvice;
import com.informationsystem.dao.SystemuserDao;
import com.informationsystem.dao.hibernate.GenericDaoHibernate;

import org.hibernate.criterion.Restrictions;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

@Repository("systemuserDao")
public class SystemuserDaoHibernate extends GenericDaoHibernate<Systemuser, Long> implements SystemuserDao,UserDetailsService{

    public SystemuserDaoHibernate() {
        super(Systemuser.class);
    }
    
    @Override
	public UserDetails loadUserByUsername(String username){
	    List users = getSession().createCriteria(Systemuser.class).add(Restrictions.eq("username", username)).list();
	    if (users == null || users.isEmpty()) {
	        return null;
	    } 
	    else{
	    	Systemuser user = (Systemuser)users.get(0);
	    	List<GrantedAuthority> authsList = new ArrayList<GrantedAuthority>();
	        for (Authority a : user.getAuthorities()) {  
	                authsList.add(new GrantedAuthorityImpl("ROLE_" + a.getName().toUpperCase()));  
	        }  
	        if(user.getType().toUpperCase().equals("ADMIN"))
	        	authsList.add(new GrantedAuthorityImpl("ROLE_ADMIN"));  
	        else
	        	authsList.add(new GrantedAuthorityImpl("ROLE_USER"));  
	    	org.springframework.security.core.userdetails.User userdetail = new org.springframework.security.core.userdetails.User(  
	    			user.getUsername(), user.getPassword(), true, true, true, true, authsList); 
	    	return userdetail;
	    }
	}

	@Override
	@Transactional
	public Systemuser getUserByUsername(String username)
			throws UsernameNotFoundException {
			List users = getSession().createCriteria(Systemuser.class).add(Restrictions.eq("username", username)).list();
		    if (users == null || users.isEmpty()) {
		        return new Systemuser();
		    } 
		    else
		    	return (Systemuser)users.get(0);
	}
}
